#-*- coding:utf-8 -*-
from django.utils.translation import get_language

from mrc_platform.settings import MRC_TOKEN, DATA_API_PROTOCOL, DATA_API_DOMAIN
import requests
import logging
log = logging.getLogger('proscenium')

def mrc_is_authenticated(request):
    '''
    2018-06-01 add by jack
    通过cookie中的token验证用户是否在授权期中
    :param request:
    :return:
    '''
    headers = {'Content-Type': 'application/json'}
    token=request.COOKIES.get(MRC_TOKEN,'')

    if token=='':
        return False
    data_dict = {"token": token,"language":get_language()}
    url = DATA_API_PROTOCOL + DATA_API_DOMAIN + '/api/v1/verify_token/'
    log.info("send data %s" %data_dict)
    try:
        response=requests.post(url,json=data_dict,headers=headers)
    except Exception as e:
        log.warning(e)
        log.warning("验证token时，出现网络错误!")
        return False
    if response.status_code != 200:
        log.warning('调用token验证接口 api错误 http返回码 %s' % response.status_code)
        return False
    data_json=response.json()
    log.info("return data %s" %data_json)
    if data_json.get('code',1)!=0:
        log.warning('token验证接口 api错误 返回错误信息 %s' % data_json.get('message', ''))
        return False
    state=data_json.get('state',False)
    if state==True:
        return True
    else:
        return False



def get_username(token):
    url=DATA_API_PROTOCOL + DATA_API_DOMAIN + '/api/v1/get_username/'
    headers={'Content-Type':'application/json','Authorization':'JWT %s' %token}
    data_dict = {"language": get_language()}
    try:
        response=requests.get(url,params=data_dict,headers=headers)
    except Exception as e:
        log.warning(e)
        log.warning('获取用户名错误,出现网络错误')
        return ''
    if response.status_code != 200:
        log.warning('调用username api错误 http返回码 %s' % response.status_code)
        return ''
    data_json=response.json()
    if data_json.get('code',1)!=0:
        log.warning('调用username api错误 返回错误信息 %s' % data_json.get('message', ''))
        return ''
    username=data_json.get('username','')
    return username


def get_user_info(token):
    url = DATA_API_PROTOCOL + DATA_API_DOMAIN + '/api/v1/get_user_info/'
    headers = {'Content-Type': 'application/json', 'Authorization': 'JWT %s' % token}
    data_dict = {"language": get_language()}
    try:
        response = requests.get(url, headers=headers,params=data_dict)
    except Exception as e:
        log.warning(e)
        log.warning('获取用户信息错误,出现网络错误')
        return {}
    if response.status_code != 200:
        log.warning('调用api错误 http返回码 %s' % response.status_code)
        log.warning('获取用户信息错误,出现网络错误')
        return {}
    user_json=response.json()
    log.info("user info: %s" %user_json)
    return user_json
